const app = getApp();
const startTop = 50;
const gapSize = 70;
const WxParse = require('../../../../wxParse/wxParse.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    article: '',
    isModal: false,
    imgDraw: {}, //绘制图片的大对象
    sharePath: '', //生成的分享图
    visible: false,
    goods: {},
    userInfo: {},
    qrcode: "",
    avatarUrl: "", //头像
    nickname: "", //昵称
    popupShow: false,
  },

  showRules() {
    this.setData({
      popupShow: true
    })
  },

  hidePopup() {
    this.setData({
      popupShow: false
    })
  },

  createQrcode(userInfo) {
    let query = `${userInfo.id},${this.goods_id}`;
    let role = wx.getStorageSync('role'); //1维修 2销售 3合伙人
    if (role == 2) {
      query = query + ",2"
    } else if (role == 3) {
      query = query + ",1"
    }
    console.log("query参数", query)
    app.ajax({
      url: "Common/Wx/getPageQr",
      data: {
        query,
        page: "pages/sellCard/buy-card/buy-card"
      },
      success: res => {
        if (res.data.code == 1000) {
          this.setData({
            qrcode: res.data.data.all_url
          });
        }
      }
    })
  },

  //分享规则
  getRule() {
    app.ajax({
      url: "Common/Common/getShareRule",
      data: {
        code: "WOI542EQ"
      },
      success: res => {
        if (res.data.code == 1000) {
          this.setData({
            article: res.data.data[0]
          })
          WxParse.wxParse('desc', 'html', res.data.data[0].content, this, 5);
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },


  getUserInfo() {
    const role = wx.getStorageSync('role'); //1维修 2销售 3合伙人
    let url;
    if (role == 2) {
      url = "Salesman/Login/getInfo";
    } else if (role == 3) {
      url = "Partner/User/getPartnerInfo";
    }
    app.ajax({
      url,
      success: res => {
        const code = res.data.code;
        if ((role == 2 && code == 1000) || (role == 3 && code == 200)) {
          let userInfo = res.data.data;
          this.setData({
            userInfo
          })
          this.createQrcode(userInfo);
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const eventChannel = this.getOpenerEventChannel();
    let _self = this;
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      _self.goods_id = data.id;
      _self.setData({
        goods: data
      })
    })
    wx.getUserInfo({
      success: res => {
        if (res.errMsg === 'getUserInfo:ok') {
          this.setData({
            avatarUrl: res.userInfo.avatarUrl,
            nickname: res.userInfo.nickName
          })
        }
      }
    })

    this.getRule(); //获取规则
    this.getUserInfo(); //获取用户信息

  },





  createCanvas() {
    this.drawPic();
  },


  handlePhotoSaved() {
    this.savePhoto(this.data.sharePath)
  },
  handleClose() {
    this.setData({
      visible: false
    })
  },
  drawPic() {
    if (this.data.sharePath) { //如果已经绘制过了本地保存有图片不需要重新绘制
      this.setData({
        visible: true
      })
      return
    }
    wx.showLoading({
      title: '生成中'
    })
    this.setData({
      imgDraw: {
        width: '750rpx',
        height: '1334rpx',
        background: '../../../images/share-content-bg.png',
        views: [{
            type: 'image',
            url: this.data.goods.card_img,
            css: {
              top: '32rpx',
              left: '30rpx',
              right: '32rpx',
              width: '688rpx',
              height: '420rpx',
              borderRadius: '16rpx'
            },
          },
          {
            type: 'image',
            url: this.data.avatarUrl || 'https://qiniu-image.qtshe.com/default-avatar20170707.png',
            css: {
              top: '380rpx',
              left: '315rpx',
              width: '120rpx',
              height: '120rpx',
              borderWidth: '6rpx',
              borderColor: '#FFF',
              borderRadius: '120rpx'
            }
          },
          {
            type: 'text',
            text: this.data.nickname || (wx.getStorageSync('role') == 2 ? this.data.userInfo.full_name : this.data.userInfo.account_name),
            css: {
              top: '532rpx',
              fontSize: '28rpx',
              left: '375rpx',
              align: 'center',
              color: '#3c3c3c'
            }
          },
          {
            type: 'text',
            text: `诚邀你一起购买水卡`,
            css: {
              top: '576rpx',
              left: '375rpx',
              align: 'center',
              fontSize: '28rpx',
              color: '#3c3c3c'
            }
          },
          {
            type: 'text',
            text: this.data.goods.card_name,
            css: {
              top: '644rpx',
              left: '365rpx',
              maxLines: 1,
              align: 'center',
              fontWeight: 'bold',
              fontSize: '64rpx',
              color: '#3c3c3c',
            }
          },

          {
            type: 'text',
            text: '长按识别图中的二维码进入小程序',
            left: "120rpx",
            css: [{
              top: `${startTop +12 * gapSize}rpx`,
              width: '280rpx',
              left: '60rpx',
              fontSize: '26rpx',
            }],
          },
          {
            type: 'image',
            url: this.data.qrcode,
            css: {
              top: '834rpx',
              left: '470rpx',
              width: '200rpx',
              height: '200rpx'
            }
          }
        ]
      }
    })
  },
  onImgErr(e) {
    wx.hideLoading()
    wx.showToast({
      title: '生成分享图失败，请重新进入页面'
    })
  },
  onImgOK(e) {
    wx.hideLoading()
    this.setData({
      sharePath: e.detail.path,
      visible: true,
    })
  },


  hideModal() {
    this.setData({
      isModal: false
    })
  },
  preventDefault() {},
  // 保存图片
  savePhoto(path) {
    wx.showLoading({
      title: '正在保存...',
      mask: true
    })
    wx.saveImageToPhotosAlbum({
      filePath: path,
      success: (res) => {
        wx.showToast({
          title: '保存成功',
          icon: 'none'
        })
        setTimeout(() => {
          this.setData({
            visible: false
          })
        }, 300)
      },
      fail: (res) => {
        wx.getSetting({
          success: res => {
            let authSetting = res.authSetting
            if (!authSetting['scope.writePhotosAlbum']) {
              this.setData({
                isModal: true
              })
            }
          }
        })
        setTimeout(() => {
          wx.hideLoading()
          this.setData({
            visible: false
          })
        }, 300)
      }
    })
  }
})